package br.com.locautowebbd.endereco;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.locautowebbd.util.HibernateConnectionUtil;
import br.com.locautowebbd.util.RepositorioException;


public class RepositorioEnderecoJPA implements RepositorioEnderecos {

	@Override
	public void atualizar(Endereco endereco) throws EnderecoInexistenteException,
			RepositorioException {
		try {
			Session session = HibernateConnectionUtil.getSession();
			Transaction t = session.beginTransaction();

			if (!existe(endereco.getCep())) {
				throw new EnderecoInexistenteException(endereco.getCep());

			}

			session.update(endereco);
			session.flush();
			t.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);
		}

	}

	@Override
	public boolean existe(int cep) throws RepositorioException {
		boolean resp = false;
		try {
			Session session = HibernateConnectionUtil.getSession();
			Transaction t = session.beginTransaction();
			Endereco procurado = (Endereco) session.get(Endereco.class, cep);
			resp = procurado != null;
			session.flush();
			t.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);
		}
		return resp;
	}

	@Override
	public void inserir(Endereco novoEndereco) throws EnderecoExistenteException,
			RepositorioException {
		try {
			if (!existe(novoEndereco.getCep())) {
				Session session = HibernateConnectionUtil.getSession();
				Transaction t = session.beginTransaction();
				session.save(novoEndereco);
				session.flush();
				t.commit();
			}
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);
		}
	}

	@Override
	public Endereco procurar(int cep) throws EnderecoInexistenteException,
			RepositorioException {
		Endereco resp = null;
		try {
			Session session = HibernateConnectionUtil.getSession();
			Transaction t = session.beginTransaction();
			resp = (Endereco) session.get(Endereco.class,cep);

			if (resp == null) {
				throw new EnderecoInexistenteException(cep);

			}
			session.flush();
			t.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);

		}
		return resp;
	}

	@Override
	public void remover(int cep) throws EnderecoInexistenteException,
			RepositorioException {
		try {
			Session session = HibernateConnectionUtil.getSession();
			Transaction t = session.beginTransaction();
			Endereco procurado = (Endereco) session.get(Endereco.class, cep);

			if (procurado == null) {
				throw new EnderecoInexistenteException(cep);

			}
			session.delete(procurado);
			session.flush();
			t.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new RepositorioException(e);

		}
	}

}
